package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.core.ParseRequestData;
import com.qf.dto.TeacherDto;
import com.qf.mapper.CourseMapper;
import com.qf.mapper.TeacherMapper;
import com.qf.mapper.impl.CourseMapperImpl;
import com.qf.mapper.impl.TeacherMapperImpl;
import com.qf.pojo.Course;
import com.qf.pojo.Page;
import com.qf.pojo.Teacher;
import com.qf.service.CourseService;
import com.qf.service.TeacherService;
import com.qf.utils.ParseRequestDataUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class TeacherServiceImpl implements TeacherService {

    private TeacherMapper teacherMapper = new TeacherMapperImpl();
    private CourseService courseService = new CourseServiceImpl();
    private CourseMapper courseMapper = new CourseMapperImpl();

    @Override
    public boolean isAdd(String username) {
        Teacher teacher = teacherMapper.getTeacher(username);
        if (teacher == null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ParseRequestData<Teacher> parseRequestData = ParseRequestDataUtils.parseRequest(request, Teacher.class, "upload\\teacher");
        Teacher tea = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        if (in == null) {
            request.setAttribute("msg", "添加失败 -- 头像不能为空");
            response.getWriter().write(JSON.toJSONString(R.fail("头像不能为空")));
            return false;
        }
        if (isAdd(tea.getUsername())) {
            OutputStream out = parseRequestData.getOut();
            teacherMapper.add(tea.getUsername(), tea.getPassword(), tea.getName(), tea.getSex(), tea.getAge(), tea.getCourseId(), tea.getPhoto());
            response.getWriter().write(JSON.toJSONString(R.success("添加成功", null)));
            //将头像存储到本地磁盘
            try {
                IOUtils.copy(in, out);
                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
        request.setAttribute("msg", "添加失败，此老师账号已存在");
        response.getWriter().write(JSON.toJSONString(R.fail("添加失败，此老师账号已存在")));
        return false;
    }

    @Override
    public void initModify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        Teacher teacher = teacherMapper.getTeacher(username);
        request.setAttribute("teacher", teacher);
        courseService.getCourses(request, response);
    }

    @Override
    public void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ParseRequestData<Teacher> parseRequestData = ParseRequestDataUtils.parseRequest(request, Teacher.class, "upload\\teacher");
        Teacher tea = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        OutputStream out = parseRequestData.getOut();
        try {
            if (tea.getPhoto() != null) {//说明用户修改头像
                teacherMapper.update(tea.getUsername(), tea.getName(), tea.getSex(), tea.getAge(), tea.getCourseId(), tea.getPhoto());
                IOUtils.copy(in, out);
            } else {
                teacherMapper.update(tea.getUsername(), tea.getName(), tea.getSex(), tea.getAge(), tea.getCourseId());
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write(JSON.toJSONString(R.success("修改成功", null)));
    }

    @Override
    public void initAddTeacher(HttpServletRequest request, HttpServletResponse response) throws IOException {
        courseService.getCourses(request, response);
    }

    @Override
    public void getTeachers(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String curPage = request.getParameter("curPage");
        int offset = (Integer.parseInt(curPage) - 1) * 10;
        List<Teacher> list = teacherMapper.getTeachers(offset, 10);
        List<TeacherDto> listDto = new ArrayList<>();
        list.forEach(teacher -> {
            TeacherDto teacherDto = new TeacherDto();
            try {
                BeanUtils.copyProperties(teacherDto, teacher);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            Course course = courseMapper.getCourse(teacher.getCourseId());
            if (course == null) {
                String jsonString = JSON.toJSONString(R.success(teacher.getName() + "老师的课程不存在", null));
                try {
                    response.getWriter().write(jsonString);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return;
            }
            teacherDto.setCourseName(course.getName());
            listDto.add(teacherDto);
        });
        Page<TeacherDto> teacherPage = new Page<>();
        teacherPage.setCurPage(Integer.parseInt(curPage));
        int total = teacherMapper.getAllCount();
        teacherPage.setTotalPage(total == 0 ? 1 : (total % 10 == 0 ? total / 10 : total / 10 + 1));
        teacherPage.setUrl("teacher?action=doGetTeachers&curPage=");
        teacherPage.setList(listDto);
        String jsonString = JSON.toJSONString(R.success("查询成功", teacherPage));
        response.getWriter().write(jsonString);
    }

    @Override
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (request.getParameter("username") == null) {
            response.getWriter().write(JSON.toJSONString(R.fail("username不能为空")));
            return;
        }
        teacherMapper.delete(request.getParameter("username"));
        response.getWriter().write(JSON.toJSONString(R.success("删除成功", null)));
    }
}
